package com.heisen.file.controller;

/**
 * @author sen
 * @description
 * @date 2024/2/27 10:44
 */

import com.heisen.base.entity.Api;
import com.heisen.base.exception.RRException;
import com.heisen.file.domin.FileStorageManager;
import com.heisen.file.dto.FileDto;
import com.heisen.security.annotation.ApiResourceOpen;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {


    @Autowired
    private FileStorageManager fileStorageManager;

    @PostMapping("/uploadFile")
    @ApiResourceOpen
    public Api uploadFile(@RequestParam(value = "files", required = true) MultipartFile[] files , FileDto fileDto) {
        log.info("【准备文件上传】 fileDto={}",fileDto);
        if(StringUtils.isEmpty(fileDto.getStoreService())) throw new RRException("服务名称为空");
        return Api.ok(fileStorageManager.upload(files ,fileDto));
    }

    @GetMapping("/fileUrl")
    @ApiResourceOpen
    public Api fileUrl(@RequestParam(value = "fileId")String fileId ) {
        log.info("【获取文件url】fileId: {}",fileId);
        return Api.ok( fileStorageManager.fileUrl(fileId));
    }


    @GetMapping("/delete")
    @ApiResourceOpen
    public Api delete(@RequestParam(value = "fileId")String fileId ) {
        log.info("【准备文件删除】fileId: {}",fileId);
        return Api.of(fileStorageManager.delete(fileId)).build();
    }

    @GetMapping("/download")
    @ApiResourceOpen
    public void download(@RequestParam(value = "fileId")String fileId, HttpServletResponse response) {
        log.info("【准备文件下载】fileId: {}",fileId);
        fileStorageManager.download(fileId,response);
    }


}
